#import "MenuController.h"

@implementation MenuController

- (id)init {
	if (self = [super initWithStyle:UITableViewStyleGrouped]) {
		groups = [NSMutableArray new];
	}
	return self;
}

- (void)dealloc {
	[groups release];
    [super dealloc];
}

#pragma mark Item Handling

- (void)clear {
	[groups removeAllObjects];
}

- (void)addMenuItemWithText:(NSString *)text tile:(UIImage *)tile {
	NSMutableArray *group = [groups lastObject];
	if (group == nil || tile == nil) {
		//! this is too quick an dirty: use a data structure
		group = [NSArray arrayWithObjects:[NSMutableArray array], 
			(tile == nil ? text : nil), nil];
		[groups addObject:group];
	}
	if (tile != nil) {
		//! this is too quick and dirty: use a data structure
		[[group objectAtIndex:0] addObject:[NSArray arrayWithObjects:text, tile, nil]];
	}
}

#pragma mark UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [groups count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[[groups objectAtIndex:section] objectAtIndex:0] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	NSArray *group = [groups objectAtIndex:section];
	if ([group count] > 1) {
		return [group objectAtIndex:1];
	} else {
		return nil;
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView
		cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
			reuseIdentifier:CellIdentifier] autorelease];
    }
	
	NSArray *itemInfo = [[[groups objectAtIndex:indexPath.section] objectAtIndex:0]
		objectAtIndex:indexPath.row];
	cell.text = [itemInfo objectAtIndex:0];
	if ([itemInfo count] > 1) {
		cell.image = [itemInfo objectAtIndex:1];
	}
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//! will need to send some sort of message back to the controller
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

@end

